<template>
  <div class="purchase-request-detail">
    <el-card v-loading="loading" class="detail-card">
      <template #header>
        <div class="card-header">
          <h3>采购申请详情</h3>
          <div v-if="purchaseRequest">
            <div class="action-buttons">
              <el-button
                v-if="purchaseRequest?.status === 'PENDING' && isCurrentUserRequest"
                type="primary"
                @click="editRequest"
              >
                编辑
              </el-button>
              <el-button
                v-if="purchaseRequest?.status === 'PENDING' && isCurrentUserRequest"
                type="danger"
                @click="confirmDelete"
              >
                删除
              </el-button>
              <el-button
                :type="purchaseRequest?.attachmentPath ? 'primary' : 'info'"
                :disabled="!purchaseRequest?.attachmentPath"
                @click="downloadAttachment"
              >
                下载附件
              </el-button>
              <el-button @click="goBack">
                返回
              </el-button>
            </div>
          </div>
        </div>
      </template>
      
      <div v-if="purchaseRequest" class="detail-content">
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="申请编号">{{ purchaseRequest.id }}</el-descriptions-item>
          <el-descriptions-item label="申请状态">
            <el-tag :type="getStatusType(purchaseRequest.status)">
              {{ getStatusText(purchaseRequest.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="物品名称">{{ purchaseRequest.itemName }}</el-descriptions-item>
          <el-descriptions-item label="数量">{{ purchaseRequest.quantity }}</el-descriptions-item>
          <el-descriptions-item label="预算">¥{{ purchaseRequest.budget?.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="申请日期">{{ formatDateTime(purchaseRequest.createdAt) }}</el-descriptions-item>
          <el-descriptions-item label="申请人">{{ getUserName(purchaseRequest.requestUser) }}</el-descriptions-item>
          <el-descriptions-item label="部门">{{ formatDepartment(purchaseRequest.requestUser) }}</el-descriptions-item>
          <el-descriptions-item label="申请原因" :span="2">{{ purchaseRequest.reason }}</el-descriptions-item>
        </el-descriptions>
        
        <el-descriptions 
          v-if="purchaseRequest.status !== 'PENDING'"
          title="审批信息" 
          :column="2" 
          border
          class="mt-20"
        >
          <el-descriptions-item label="审批结果">
            <el-tag :type="purchaseRequest.status === 'APPROVED' ? 'success' : 'danger'">
              {{ purchaseRequest.status === 'APPROVED' ? '通过' : '拒绝' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="审批日期">{{ formatDateTime(purchaseRequest.approvalDate) }}</el-descriptions-item>
          <el-descriptions-item label="审批人">
            {{ purchaseRequest.approver ? (purchaseRequest.approver.name || purchaseRequest.approver.username) : '未知' }}
          </el-descriptions-item>
          <el-descriptions-item label="审批意见" :span="2">{{ purchaseRequest.approvalComment || '无' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      
      <el-empty v-else-if="!loading" description="未找到申请信息"></el-empty>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getPurchaseRequestById, deletePurchaseRequest } from '@/api/purchase-request'
import { useAuthStore } from '@/store/auth'
import { formatDateTime, getPurchaseStatusType, getStatusText } from '@/utils/format'

const authStore = useAuthStore()
const router = useRouter()
const route = useRoute()
const id = route.params.id
const loading = ref(true)
const purchaseRequest = ref(null)

// 判断当前用户是否是申请人
const isCurrentUserRequest = computed(() => {
  if (!purchaseRequest.value || !purchaseRequest.value.requestUser) return false
  const requestUserId = purchaseRequest.value.requestUser.id
  return requestUserId === authStore.userInfo.id
})

// 获取采购申请状态对应的Element Plus标签类型
const getStatusType = (status) => {
  const typeMap = {
    'PENDING': 'warning',
    'APPROVED': 'success',
    'REJECTED': 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取采购申请详情
const fetchPurchaseRequest = async () => {
  loading.value = true
  try {
    const response = await getPurchaseRequestById(id)
    
    // 检查响应格式，确保正确设置purchaseRequest的值
    if (response) {
      purchaseRequest.value = response
      console.log('获取的采购申请详情：', purchaseRequest.value)
    } else {
      ElMessage.error('获取采购申请详情失败：响应格式错误')
      purchaseRequest.value = null
    }
  } catch (error) {
    console.error('获取采购申请详情失败:', error)
    ElMessage.error('获取采购申请详情失败: ' + (error.message || '未知错误'))
    purchaseRequest.value = null
  } finally {
    loading.value = false
  }
}

// 编辑申请
const editRequest = () => {
  router.push(`/purchase-requests/${id}/edit`)
}

// 确认删除
const confirmDelete = () => {
  ElMessageBox.confirm(
    '确定要删除这条采购申请吗？此操作不可逆。',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    deleteRequest()
  }).catch(() => {})
}

// 删除申请
const deleteRequest = async () => {
  try {
    await deletePurchaseRequest(id)
    ElMessage.success('删除成功')
    router.push('/purchase-requests')
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败: ' + (error.message || '未知错误'))
  }
}

// 下载附件
const downloadAttachment = () => {
  if (purchaseRequest.value?.attachmentPath) {
    console.log('开始下载附件:', purchaseRequest.value.attachmentPath);
    // 使用axios直接获取文件，避免401错误
    const token = localStorage.getItem('token');
    console.log('认证token:', token ? '已获取' : '未获取');
    
    // 下载URL
    const downloadUrl = `/api/purchase-requests/${purchaseRequest.value.id}/attachment`;
    console.log('下载URL:', downloadUrl);
    
    // 添加认证头
    if (token) {
      // 为了在下载时带上token，我们需要使用Blob和fetch API
      ElMessage.info('正在下载附件，请稍候...');
      
      fetch(downloadUrl, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })
      .then(response => {
        console.log('下载响应状态:', response.status, response.statusText);
        if (!response.ok) {
          return response.text().then(text => {
            console.error('下载错误详情:', text);
            throw new Error(`下载失败: ${response.status} ${response.statusText}`);
          });
        }
        return response.blob();
      })
      .then(blob => {
        console.log('获取到blob数据:', blob.type, blob.size);
        
        // 创建一个临时URL
        const url = window.URL.createObjectURL(blob);
        
        // 创建下载链接
        const link = document.createElement('a');
        link.href = url;
        
        // 设置文件名
        link.download = purchaseRequest.value.attachmentPath;
        console.log('设置下载文件名:', link.download);
        
        // 模拟点击下载
        document.body.appendChild(link);
        link.click();
        
        // 清理
        window.URL.revokeObjectURL(url);
        document.body.removeChild(link);
        
        ElMessage.success('附件下载成功');
      })
      .catch(error => {
        console.error('下载附件失败:', error);
        ElMessage.error('下载附件失败: ' + error.message);
      });
    } else {
      ElMessage.error('未获取到认证信息，请重新登录');
    }
  } else {
    ElMessage.warning('该申请没有附件');
  }
}

// 返回列表
const goBack = () => {
  router.go(-1)
}

// 获取用户名
const getUserName = (user) => {
  if (!user) return '未知'
  return user.name || user.username || '未知'
}

// 格式化部门名称
const formatDepartment = (user) => {
  if (!user) return '未知'
  return user.department || '未知'
}

onMounted(() => {
  fetchPurchaseRequest()
})
</script>

<style scoped>
.purchase-request-detail {
  padding: 20px;
}

.detail-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-buttons .el-button {
  margin-left: 10px;
}

.action-buttons .el-button:first-child {
  margin-left: 0;
}

.detail-content {
  padding: 20px 0;
}

.mt-20 {
  margin-top: 20px;
}
</style> 